 <template>
  <div>
    <el-form ref="form" :model="data" label-width="80px">
      <!-- <el-form-item label="姓名">
        <el-input v-model="data.name" type="text" placeholder="请输入名称" />
      </el-form-item> -->
      <el-form-item label="店铺分组">
        <el-cascader
          class="region"
          v-model="data.salesGrade"
          placeholder="选择店铺分组"
          :options="cascadeList"
          :props="{ checkStrictly: true }"
          @change="handleChange"
          style="width: 300px; height: 30px"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item>
        <!--<el-upload
                    ref="upload" # 插眼
                    action="" # 原来的提交方法，这里我们把他覆盖了
                    class="upload-demo"
                    :http-request="httpRequest" # 覆盖原本的提交方法，我们指定一个函数，在其中完成参数的提取，当然你也可以在其他的需求中对他进行直接提交
                    :on-preview="handlePreview" # 当点击已上传的文件时执行的函数
                    :multiple="false" # 是否允许多文件提交
                    :limit="1" # 最大支持上传的文件数量
                    :auto-upload="false" # 关闭自动提交
                    :file-list="data.file" # 文件数据存储的位置,这里只是元数据，文件流只有真正提交的时候才会拥有
                >-->
        <el-upload
          ref="upload"
          :headers="Upload.headers"
          action=""
          class="upload-demo"
          :http-request="httpRequest"
          :on-change="getFile"
          :multiple="false"
          :limit="1"
          :auto-upload="false"
          :file-list="data.file"
        >
          <el-button size="small" type="primary">选择头像</el-button>
        </el-upload>
        <!-- <el-upload
          :action="Upload.url"
          :headers="Upload.headers"
          :limit="limit"
          :on-exceed="handleExceed"
          :on-success="handlePictureSuccessPic"
          :before-upload="beforeAvatarUpload"
          :file-list="fileLi"
          :on-change="changeFile1"
        >
          <el-button size="small" type="primary">导入文件</el-button>
        </el-upload> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
import {
  listBrandChannelShop,
  importBiKeyword,
} from "@/api/chart/brandChannelShop";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "upload",
  data() {
    return {
      fileLi: [],
      dialogVisible: false,
      limit: 2,
      Upload: {
        // 设置上传的请求头部
        headers: {
          header: { responseType: "blob" },

          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url:
          process.env.VUE_APP_BASE_API +
          "/product/BiKeywordDwd/importBiKeyword",
      },

      cascadeList: [],
      data: {
        salesGrade: ["VFU"],
        name: "tom",
        age: 18,
      },
    };
  },
  created() {
    this.getdataSourceList();
  },
  methods: {
    //店铺控件
    handleChange(val) {
      console.log(JSON.stringify(val));
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }
      this.openUploadLoading();
      return isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.picUrl = file.url;
      this.imageUrl = file.url;
      // this.dialogVisible = true;
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openUploadLoading() {
      this.$modal.loading("正在导入，请稍候！");
    },
    //文件导入成功回传

    handlePictureSuccessPic(response, file) {
      console.log(JSON.stringify(file));
      console.log(JSON.stringify(response));
      this.dialogVisible = false;
      this.$modal.closeLoading();
      this.openmsg = true;
      this.msg = response.msg;

      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.picUrl = file.response.url;
      // const url = file.response.fileName;
      // this.file = file.response.url;
      // console.log(JSON.stringify(this.file));
      // if (res.code == 200) {

      //   this.dialogVisible = false

      //   if (res.msg == '操作成功') {

      //     this.$modal.msgSuccess('导入成功')
      //   } else {
      //     this.$modal.msgError(res.msg);
      //   }
      //   this.getList();
      //   // return true
      // } else {
      //   this.$modal.msgError(res.msg);
      //   this.dialogVisible = true
      //   // this.$message.msgError('该颜色未在字典定义')
      //   return
      // }
    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传文件让第二次覆盖第一的文件
    changeFile1(file, fileList) {
      if (fileList.length > 1) {
        this.fileLi = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
    httpRequest(param) {
      //把上传的文件赋值给data属性的file
      this.data.file = param.file;
      console.log(JSON.stringify(param));
    },
    getFile(file, fileList) {
      const fd = new FormData(); // FormData 对象
      console.log(JSON.stringify(fd));
    },
    /* 提交修改*/
    onSubmit() {
      //注意执行submit方法后，他会触发upload组件中的 http-request
      this.$refs.upload.submit();
      // 新建form表单
      const formData = new FormData();
      // this.$set(formData, "name", this.data.name);
      // this.$set(formData, "age", this.data.age);
      this.$set(formData, "file", this.data.file);
      this.$set(formData, "salesGrade", this.data.salesGrade);

      console.log(JSON.stringify(formData));
      // formData.append("name", this.data.name);
      // formData.append("age", this.data.age);
      // formData.append("file", this.data.file);
      let config = {
        header: {
          // Authorization: "Bearer " + getToken(),
          "Content-Type": "multipart/form-data",
        },
      };
      importBiKeyword(formData, config).then((response) => {
        console.log(response);
      });
      // console.log(
      //   JSON.stringify(
      //     process.env.VUE_APP_BASE_API + "/product/BiKeywordDwd/importBiKeyword"
      //   )
      // );
      // return;
      // axios
      //   .post(
      //     process.env.VUE_APP_BASE_API +
      //       "/product/BiKeywordDwd/importBiKeyword",
      //     formData
      //   )
      //   .then((response) => {
      //     alert(response.data);
      //   });
    },
    /** 查询品牌渠道店铺关系列表 */
    getdataSourceList() {
      listBrandChannelShop().then((response) => {
        let result = this.transformData(response.rows);
        this.cascadeList = result;
      });
    },
    //店铺渠道品牌转换

    transformData(data) {
      let result = [];

      data.forEach((item) => {
        let brand = item.brand;
        let channel = item.channel;
        let shopName = item.shopName;

        // 如果brand在结果数组中不存在，则创建一个新的数组
        let brandIndex = result.findIndex(
          (brandObj) => brandObj.label === brand
        );
        if (brandIndex === -1) {
          result.push({
            label: brand,
            value: brand,
            children: [],
          });
          brandIndex = result.length - 1;
        }

        // 如果channel在当前brand的children数组中不存在，则创建一个新的数组
        let channelIndex = result[brandIndex].children.findIndex(
          (channelObj) => channelObj.label === channel
        );
        if (channelIndex === -1) {
          result[brandIndex].children.push({
            label: channel,
            value: channel,
            children: [],
          });
          channelIndex = result[brandIndex].children.length - 1;
        }

        // 如果shopName在当前channel的children数组中不存在，则创建一个新的数组
        let shopIndex = result[brandIndex].children[
          channelIndex
        ].children.findIndex((shopObj) => shopObj.label === shopName);
        if (shopIndex === -1) {
          result[brandIndex].children[channelIndex].children.push({
            label: shopName,
            value: shopName,
            // children: []
          });
        }
      });

      return result;
    },
  },
};
</script>
 

 

 